package net.zoneland.knowledge.controller;

import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import net.zoneland.knowledge.controller.bean.SanHuiYiKeVo;
import net.zoneland.knowledge.enums.CompanyEnum;
import net.zoneland.knowledge.enums.DiYiYiTiReportColumnEnum;
import net.zoneland.knowledge.exceptions.DjExceptionCode;
import net.zoneland.knowledge.model.DiYiYiTi;
import net.zoneland.knowledge.model.LoginUserPojo;
import net.zoneland.knowledge.model.ResponseResultRest;
import net.zoneland.knowledge.service.DiYiYiTiService;
import net.zoneland.knowledge.utils.DiYiYiTiReportColumnHandler;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 第一议题控制类.
 * @author zx
 */
@RestController()
@RequestMapping("/diYiYiTi")
@Slf4j
public class DiYiYiTiController extends  BaseController {

    @Autowired
    private DiYiYiTiService diYiYiTiService;

    /**
     * 文件名.
     */
    private static final String FILENAME = "“第一议题”和党委中心组学习巡检";

    /**
     * 查询.
     * @param request http请求
     * @param vo 查询参数对象
     * @return 用户集合响应结果
     */
    @PostMapping("/query")
    public ResponseResultRest query(HttpServletRequest request, @RequestBody SanHuiYiKeVo vo) {
        return ResponseResultRest.success(diYiYiTiService.searchList(vo));
    }

    /**
     * 查询.
     * @param request http请求
     * @param vo 查询参数对象
     * @return 用户集合响应结果
     */
    @PostMapping("/queryByGroup")
    public ResponseResultRest queryByGroup(HttpServletRequest request, @RequestBody SanHuiYiKeVo vo) {
        final PageInfo<DiYiYiTi> page = diYiYiTiService.searchToPage(vo);
        final List<DiYiYiTi> diYiYiTiList = page.getList();
        final TreeMap<String, List<DiYiYiTi>> listTreeMap = diYiYiTiList.stream().collect(
                Collectors.groupingBy(
                        bean -> {
                            String companyName = bean.getCompanyName();
                            if (StringUtils.isBlank(companyName)) {
                                companyName = CompanyEnum.OTHER.getName();
                            }
                            return companyName;
                        },
                        /**() -> new TreeMap<>((Comparator.reverseOrder())),*/
                        () -> new TreeMap<>((o1, o2) -> {
                            try {
                                final CompanyEnum key1 = CompanyEnum.getEnumByName(o1);
                                final CompanyEnum key2 = CompanyEnum.getEnumByName(o2);
                                return key1.getOrder() - key2.getOrder();
                            } catch (Exception e) {
                                //
                            }
                            return 0;
                        }),
                        Collectors.toList()));

        final long count = page.getTotal() > page.getPageSize() ? page.getTotal() - page.getPageSize() : listTreeMap.size();
        return ResponseResultRest.success(listTreeMap, (int)count);
    }

    /**
     * 查询.
     * @param request http请求
     * @param id 查询参数对象
     * @return 用户集合响应结果
     */
    @GetMapping("/getInfoById")
    public ResponseResultRest getInfoById(final String id, HttpServletRequest request) {
        Preconditions.checkNotNull(id, DjExceptionCode.DJ_ID_NULL);
        return ResponseResultRest.success(diYiYiTiService.getInfoById(id));
    }

    /**
     * pc端文件导出.
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/download")
    public void batchDownPc(final HttpServletRequest request, final HttpServletResponse response, @RequestBody final SanHuiYiKeVo vo, final String token) {
        batchDown(response, vo);
    }

    /**
     * 文件导出.
     * @param response
     * @param vo 第一议题参数
     */
    private void batchDown(final HttpServletResponse response, @RequestBody final SanHuiYiKeVo vo) {
        try {
            setExcelRespProp(response, FILENAME);
            final List<DiYiYiTi> diYiYiTiList = diYiYiTiService.searchList(vo);
            final List<Integer> list = Arrays.asList(DiYiYiTiReportColumnEnum.COLUMN_INDEX_TWO.getIntKey(), DiYiYiTiReportColumnEnum.COLUMN_INDEX_FOUR.getIntKey());
            this.write(response, DiYiYiTi.class, new DiYiYiTiReportColumnHandler(), FILENAME, diYiYiTiList, vo, list);
        } catch (IOException e) {
            log.error("batchDown error {} : " , vo, e);
        }

    }

    /**
     * moa端导出get.
     * @param request http请求
     * @param response response响应
     * @param sanHuiYiKeVo 第一议题巡检参数
     * @param token moa端带token
     */
    @ResponseBody
    @RequestMapping(value = "/downloadGet", method = RequestMethod.GET)
    public void downloadGet(final HttpServletRequest request, final HttpServletResponse response, final SanHuiYiKeVo sanHuiYiKeVo, final String token) {
        try {
            sanHuiYiKeVo.setMeetingName(URLDecoder.decode(sanHuiYiKeVo.getMeetingName(), StandardCharsets.UTF_8.name()));
            batchDown(response, sanHuiYiKeVo);
        } catch (UnsupportedEncodingException e) {
            log.error("URLDecoder error {}:", sanHuiYiKeVo, e);
        }
    }

}
